from django.contrib import admin
from import_export.admin import ImportExportModelAdmin
from apps.weld.models import *


# Register your models here.

class WeldListInline(admin.TabularInline):
    model = WeldList
    extra = 10
    style = 'table'


class WeldAdmin(ImportExportModelAdmin):
    list_display = ('my_id', 'show_pcb_image', 'show_author_image', 'num', 'get_goods_num', 'date_joined', 'desc')
    list_filter = ['author__name', 'date_joined']
    list_per_page = 10
    search_fields = ['my_id', 'pcb__my_id']
    radio_fields = {"author": admin.HORIZONTAL, }
    inlines = [WeldListInline]

    def get_goods_num(self, obj):
        receipt_lists = obj.weldlist_set.all()
        goods_num = receipt_lists.__len__()
        return goods_num

    get_goods_num.short_description = "元件种数"

    def save_model(self, request, obj, form, change):
        obj.pcb.stock -= obj.num
        obj.pcb.save()
        obj.save()

    def save_formset(self, request, form, formset, change):
        instances = formset.save()
        for instance in instances:
            instance.goods.stock -= instance.num
            instance.goods.save()
            instance.save()

    def delete_model(self, request, obj):
        weld_lists = obj.weldlist_set.all()
        for weld_list in weld_lists:
            weld_list.goods.stock += weld_list.num
            weld_list.goods.save()
        obj.pcb.stock += obj.num
        obj.pcb.save()
        obj.delete()


class WeldListAdmin(ImportExportModelAdmin):
    list_display = ('weld_my_id', 'order', 'goods_name', 'num', 'desc')
    list_display_links = ['order']
    list_filter = ['weld__my_id']
    list_per_page = 20
    ordering = ['weld', 'order']
    search_fields = ['weld__my_id', 'weld__pcb__my_id', 'goods__my_id', 'goods__name']

    def save_model(self, request, obj, form, change):
        obj.goods.stock -= obj.num
        obj.goods.save()
        obj.save()

    def delete_model(self, request, obj):
        obj.goods.stock += obj.num
        obj.goods.save()
        obj.delete()


admin.site.register(Weld, WeldAdmin)
admin.site.register(WeldList, WeldListAdmin)
